/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gen2phen.labs.services;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.photos.SearchParameters;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xml.sax.SAXException;

/**
 *
 * @author pedrolopes
 *
 * GEN2PHEN Semantic Web Labs: Knowledge Mashup
 *
 */
public class Flicks {

    /**
     * Search Flicrk for the given search term.
     *
     * @param query Search term.
     * @return A PhotoList object containing the 10 most relevant photos matching the search term.
     * @throws MalformedURLException
     * @throws IOException
     * @throws SAXException
     * @throws FlickrException
     */
    public static PhotoList search(String query) throws MalformedURLException, IOException, SAXException, FlickrException {

        Flickr f = new Flickr("a2cd4bd0a5709e1d043d9ac5c39068a4"); // Flicrk API key

        PhotosInterface pi = f.getPhotosInterface();

        SearchParameters sp = new SearchParameters();
        sp.setText(query);  // set the search query
        sp.setSort(SearchParameters.RELEVANCE); // set the search sorting order

        return pi.search(sp, 10, 1); //perform the search directly to return
    }

    /**
     * Get the full HTML output for a Flickr search results.
     *
     * @param query The search term.
     * @return The fully formatted HTML to be displayed on the web application
     */
    public static String get(String query) {
        String html = "";
        try {
            PhotoList photos = search(query);

            for (Object o : photos) {
                Photo p = (Photo) o;

                // add photo thumbnail and address to final HTML
                html += "<a href=\"" + p.getUrl() + "\" target=\"_blank\"><img src=\"" + p.getThumbnailUrl() + "\" /></a>";
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(Flicks.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Flicks.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(Flicks.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FlickrException ex) {
            Logger.getLogger(Flicks.class.getName()).log(Level.SEVERE, null, ex);
        }

        return html;
    }
}
